package org.mobile.servlets;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.mobile.beans.Phone;
import org.mobile.logic.PhoneLogic;

/**
 * Servlet implementation class AddPhone
 */
@WebServlet(name = "addPhone", urlPatterns = { "/addPhone" })
public class AddPhone extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddPhone() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Phone phone = new Phone();
		String price=request.getParameter("price");
		String model= request.getParameter("model");
		if(!price.isEmpty() && !model.isEmpty()){
			
			try {
				BeanUtils.populate(phone, request.getParameterMap());
				String gorrilla= request.getParameter("gorillaglass")==null? "0":"1";
				String focus= request.getParameter("autofocus")==null? "0":"1";
				String hsdpaitd = (request.getParameter("hsdpa") == null ? "0"
						: "1")
						+ (request.getParameter("hsupa") == null ? "0" : "1")
						+ (request.getParameter("hspa") == null ? "0" : "1")
						+ (request.getParameter("hspa_pl") == null ? "0" : "1")
						+ (request.getParameter("wifi") == null ? "0" : "1");
				phone.setHsdpaitd(Integer.parseInt(hsdpaitd));
				phone.setAutofocus(Integer.parseInt(focus));
				phone.setGorillaglass(Integer.parseInt(gorrilla));
				if(!PhoneLogic.getInstance().addPhone(phone)){
					request.setAttribute("error", "Błąd dodawania telefonu!");
					request.getRequestDispatcher("errPage.jsp").forward(request, response);
				}
				else{
					request.getSession().setAttribute("phones", PhoneLogic.getInstance().getAllPhones());
					response.sendRedirect("index.jsp");//wpisz sobie stron� jak� chcesz
				}
				
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
		request.setAttribute("error", "Błąd dodawania telefonu!");
		request.getRequestDispatcher("errPage.jsp").forward(request, response);
		}
	}

}
